import api.IButterKnife;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.generation.actions.BaseGenerateAction;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.PsiUtilBase;
import model.Element;
import util.Utils;
import writer.AutoWriter;

import javax.swing.*;
import java.util.ArrayList;

/**
 * Created by jiao on 16/4/23.
 */
public class AutoCreateAction extends BaseGenerateAction {

    public AutoCreateAction() {
        super(null);
    }

    public AutoCreateAction(CodeInsightActionHandler handler) {
        super(handler);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
//        Messages.showMessageDialog("终于可以啦", "这个是标题", Messages.getInformationIcon());
        Project project = e.getData(PlatformDataKeys.PROJECT);
        Editor editor = e.getData(PlatformDataKeys.EDITOR);

        PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
        PsiFile layout = Utils.getLayoutFileFromCaret(editor, file);

        if (layout == null) {
            Utils.showErrorNotification(project, "No layout found");
            return; // no layout found
        }

        ArrayList<Element> elements = Utils.getIDsFromLayout(layout);
        if (!elements.isEmpty()) {
            showDialog(project, editor, elements);
        } else {
            Utils.showErrorNotification(project, "No IDs found in layout");
        }
    }

    protected void showDialog(Project project, Editor editor, ArrayList<Element> elements) {
        PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
        if (file == null) {
            return;
        }
        PsiClass clazz = getTargetClass(editor, file);
        StringBuilder builder = new StringBuilder(clazz.getQualifiedName()).append("\n");
        for (Element e : elements) {
            builder.append("private")
                    .append(" ")
                    .append(e.name)
                    .append(" ")
                    .append(e.fieldName)
                    .append(";\n");
            //T(builder);
        }

        int offset = editor.getCaretModel().getOffset();
        PsiElement currentElement = file.findElementAt(offset - 1);
        new AutoWriter(clazz, file, currentElement, "AutoWriter", elements).execute();
    }

    public void T(Object s) {
        Messages.showInfoMessage(String.valueOf(s), "蘑菇信息");
    }


}
